import wx
import os
import time
import json
import shutil


import config
import public


class mListCtrl(wx.ListCtrl):
    def __init__(self, parent):
        wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)
        self._mchecked = False
        self._msetdict = {}
        self._msetlist = []
        self.EnableCheckBoxes()
        self.InsertColumn(0, "择", wx.LIST_FORMAT_CENTRE)
        self.InsertColumn(1, "笔记名称")
        self._width()
        pmenu = wx.Menu()
        public.myMenu(self, pmenu, ("打开笔记","删除笔记"))
        pmenu.AppendSeparator()
        self._menu = pmenu.Append(-1, "删除所有勾选", "")
        self.Bind(wx.EVT_MENU, lambda eve, menu=0 : self.on_menu(eve, k), self._menu)
        self.Bind(wx.EVT_CONTEXT_MENU, lambda eve, menu=pmenu : self.on_ShowPopup(eve, menu))
        self.Bind(wx.EVT_LIST_COL_CLICK, self.on_click)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_Select)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_ItemActivated)
        wx.CallAfter(self.on_create)


    def _width(self):
        self.SetColumnWidth(0, -1)
        self.SetColumnWidth(1, -1)

    def on_create(self):
       for k in os.listdir(config.M_PATH):
            #self.Append(('', k))
            setpath = os.path.join(config.M_PATH, k, "setting.json")
            _id = time.strftime("%Y%m%d%H%M%S") + str(time.time()).replace(".","")
            if not os.path.exists(setpath):
                dic = {"name": k , "id": _id, "startime": time.strftime("%Y-%m-%d %H:%M:%S")}
                new_path = os.path.join(config.M_PATH, _id)
                os.mkdir(new_path)
                shutil.move(os.path.join(config.M_PATH, k), new_path)
                with open(os.path.join(new_path, "setting.json"), "w", encoding="utf-8") as f:
                    f.write(json.dumps(dic))
            else:
                with open(setpath, "r", encoding="utf-8") as f:
                    try:
                        dic = json.loads(f.read())
                    except json.JSONDecodeError:
                        wx.MessageBox(k + "读取配置失败", caption="加载配置失败", style=wx.OK|wx.CENTRE, parent=self)
                        continue
            if dic.get("name") and dic.get("id") and dic.get("startime"):
                _id = dic.get("id")
                self._msetdict.update({_id : dic })
                self._msetlist.append(_id)
                index = self.InsertItem(self.GetItemCount(), "")
                self.SetItem(index, 1, dic.get("name"))

    def on_click(self, eve):
        if eve.Column == 0:
            item = wx.ListItem()
            if self._mchecked:
                self._mchecked = False
                item.SetText("择")
            else:
                item.SetText("消")
                self._mchecked = True
            self.SetColumn(0, item)
            for i in range(self.GetItemCount()):
                self.CheckItem(i, self._mchecked)

    def on_ItemActivated(self, eve):
        toggle = not self.IsItemChecked(eve.Index)
        self.CheckItem(eve.Index, toggle)

    def on_ShowPopup(self, eve, menu):
        if self.GetFirstSelected() != -1:
            if self._mchecked:
                menu.Enable(self._menu.GetId(),True)
            else:
                menu.Enable(self._menu.GetId(),False)
            pos = eve.GetPosition()
            pos = self.ScreenToClient(pos)
            self.PopupMenu(menu, pos)

    def on_menu(self, eve, value):
        if value == 0:
            _dic = self._msetdict[self._msetlist[self.GetFirstSelected()]]
            parent = self.GetParent().GetParent()
            parent.book.on_deleteAll()
            parent.textbok.SetLabel(_dic['name'])
            parent.mtree.mupdate(os.path.join(config.M_PATH, _dic['id'], _dic['name']))
            parent.OnshuBook(eve)
        print(eve, value, self._msetdict[self._msetlist[self.GetFirstSelected()]])

    def on_Select(self, eve):
        print(self._msetlist[self.GetFirstSelected()])
        m_id = self.GetItem(self.GetFirstSelected())
        parent = self.GetParent().GetParent()
        if not parent.setting.IsShown():
            parent.setting.Show(True)
        parent.setting.on_setdata(self._msetdict[self._msetlist[self.GetFirstSelected()]])    
        parent.Layout()
        eve.Skip()

